package com.lonely.inventory.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.core.page.Condition;
import com.lonely.common.enums.DataScope;
import com.lonely.common.threadlocals.DataPermissionThreadLocal;
import com.lonely.common.utils.JsonUtil;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.inventory.domain.dto.surplus.flowwater.SurplusInventoryFlowWaterComparisonDataDTO;
import com.lonely.inventory.domain.dto.surplus.flowwater.SurplusInventoryFlowWaterPageQueryDto;
import com.lonely.inventory.domain.entity.SysSurplusInventory;
import com.lonely.inventory.domain.entity.SysSurplusInventoryFlowWater;
import com.lonely.inventory.domain.entity.SysSurplusInventorySizeInfo;
import com.lonely.inventory.domain.vo.surplus.flowwater.SurplusInventoryFlowWaterPageQueryVo;
import com.lonely.inventory.mapper.SysSurplusInventoryFlowWaterMapper;
import com.lonely.inventory.service.ISurplusInventoryFlowWaterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/9/23 15:33
 * @description: 尾货库存流水服务实现类
 */
@Service
public class SurplusInventoryFlowWaterServiceImpl extends ServiceImpl<SysSurplusInventoryFlowWaterMapper, SysSurplusInventoryFlowWater> implements ISurplusInventoryFlowWaterService {


    /**
     * 分页查询
     *
     * @param queryDto
     * @return
     */
    @Override
    public Page<SurplusInventoryFlowWaterPageQueryVo> page(SurplusInventoryFlowWaterPageQueryDto queryDto) {
        DataPermissionThreadLocal.setDataPermission(DataScope.ORDER_FACTORY, "o.factory_permission");
        Page<SurplusInventoryFlowWaterPageQueryVo> page = Condition.page(queryDto);
        page = super.getBaseMapper().page(page, queryDto);

        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.setRecords(page.getRecords().stream().peek(x -> {
                List<SurplusInventoryFlowWaterComparisonDataDTO> beforeData = new ArrayList<>();
                if (StrUtil.isNotBlank(x.getBeforeDataStr())) {
                    beforeData = JsonUtil.parseArray(x.getBeforeDataStr(), SurplusInventoryFlowWaterComparisonDataDTO.class);
                }

                List<SurplusInventoryFlowWaterComparisonDataDTO> afterData = new ArrayList<>();
                if (StrUtil.isNotBlank(x.getAfterDataStr())) {
                    afterData = JsonUtil.parseArray(x.getAfterDataStr(), SurplusInventoryFlowWaterComparisonDataDTO.class);
                }

                x.setBeforeData(beforeData);
                x.setAfterData(afterData);
            }).collect(Collectors.toList()));
        }
        return page;
    }

    /**
     * 添加流水
     *
     * @param sysSurplusInventory
     * @param newSurplusInventorySizeInfos
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addFlowWater(SysSurplusInventory sysSurplusInventory,
                             List<SysSurplusInventorySizeInfo> oldSurplusInventorySizeInfos,
                             List<SysSurplusInventorySizeInfo> newSurplusInventorySizeInfos) {
        Assert.notEmpty(newSurplusInventorySizeInfos, "没有更新后的尺码信息...");

        SysSurplusInventoryFlowWater inventoryFlowWater = new SysSurplusInventoryFlowWater();
        inventoryFlowWater.setSurplusInventoryId(sysSurplusInventory.getId());

        // 提取尺码信息
        List<String> sizeNames = newSurplusInventorySizeInfos.stream().map(SysSurplusInventorySizeInfo::getSizeName).collect(Collectors.toList());

        // 处理操作前数据
        List<SurplusInventoryFlowWaterComparisonDataDTO> beforeData;
        if (CollUtil.isEmpty(oldSurplusInventorySizeInfos)) {
            beforeData = sizeNames.stream().map(x -> {
                SurplusInventoryFlowWaterComparisonDataDTO comparisonDataDTO = new SurplusInventoryFlowWaterComparisonDataDTO();
                comparisonDataDTO.setSizeName(x);
                comparisonDataDTO.setInventoryStockQuantity(0);
                return comparisonDataDTO;
            }).collect(Collectors.toList());
        } else {
            Map<String, Integer> oldSizeQuantityMap = oldSurplusInventorySizeInfos.stream().collect(Collectors.toMap(SysSurplusInventorySizeInfo::getSizeName, SysSurplusInventorySizeInfo::getInventoryStockQuantity, (x, y) -> x));
            beforeData = sizeNames.stream().map(x -> {
                SurplusInventoryFlowWaterComparisonDataDTO comparisonDataDTO = new SurplusInventoryFlowWaterComparisonDataDTO();
                comparisonDataDTO.setSizeName(x);
                comparisonDataDTO.setInventoryStockQuantity(MapUtil.getInt(oldSizeQuantityMap, x, 0));
                return comparisonDataDTO;
            }).collect(Collectors.toList());
        }
        inventoryFlowWater.setBeforeData(JsonUtil.toJsonString(beforeData));

        // 处理操作后数据
        List<SurplusInventoryFlowWaterComparisonDataDTO> afterData = newSurplusInventorySizeInfos.stream().map(x -> {
            SurplusInventoryFlowWaterComparisonDataDTO comparisonDataDTO = new SurplusInventoryFlowWaterComparisonDataDTO();
            comparisonDataDTO.setSizeName(x.getSizeName());
            comparisonDataDTO.setInventoryStockQuantity(ObjectUtil.defaultIfNull(x.getInventoryStockQuantity(), 0));
            return comparisonDataDTO;
        }).collect(Collectors.toList());
        inventoryFlowWater.setAfterData(JsonUtil.toJsonString(afterData));
        inventoryFlowWater.setCreateBy(SecurityUtils.getUserId());
        inventoryFlowWater.setUpdateBy(SecurityUtils.getUserId());

        super.save(inventoryFlowWater);

    }
}
